package com.qk.aspect;

import com.qk.entity.OperateLog;
import com.qk.mapper.OperateLogMapper;
import com.qk.utils.CurrentUserHoler;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class OperateLogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.qk.anno.Log)")
    public Object log(ProceedingJoinPoint pjp) throws Throwable {
        OperateLog OperateLog = new OperateLog();
        OperateLog.setOperateUserId(CurrentUserHoler.getCurrentUser());
        OperateLog.setOperateTime( LocalDateTime.now()) ;
        OperateLog.setClassName(pjp.getTarget().getClass().getName());
        OperateLog.setMethodName(pjp.getSignature().getName());
        OperateLog.setMethodParams(Arrays.toString(pjp.getArgs()));

        //调用原始方法运行
        long start = System.currentTimeMillis();
        Object result = pjp.proceed();
        OperateLog.setReturnValue(result.toString());
        long end = System.currentTimeMillis();
        OperateLog.setCostTime(end - start);

        //保存操作日志
        operateLogMapper.insert( OperateLog);
        return result;
    }
}
